// 排行榜API
import { NextRequest } from 'next/server';
import { LeaderboardDB } from '@/lib/mysql';
import { getCurrentUser, ApiResponse } from '@/lib/auth';

// 获取排行榜
export async function GET(request: NextRequest) {
  try {
    // 验证用户登录
    const currentUser = getCurrentUser();
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 开发模式：返回Mock数据避免数据库错误
    if (process.env.NODE_ENV === 'development') {
      try {
        const { searchParams } = new URL(request.url);
        const type = searchParams.get('type') || 'total';
        
        // 尝试获取真实数据
        let leaderboard = [];
        if (type === 'weekly') {
          leaderboard = await LeaderboardDB.getWeeklyLeaderboard(50);
        } else if (type === 'monthly') {
          leaderboard = await LeaderboardDB.getMonthlyLeaderboard(50);
        } else {
          leaderboard = await LeaderboardDB.getTotalLeaderboard(50);
        }
        
        if (leaderboard.length === 0) {
          // 没有数据，返回Mock
          console.log('⚠️ 排行榜暂无数据，返回Mock数据');
          return ApiResponse.success({
            type,
            leaderboard: [
              { id: 1, username: 'demo1', display_name: '示例用户1', total_correct: 100, rank_position: 1 },
              { id: 2, username: 'demo2', display_name: '示例用户2', total_correct: 80, rank_position: 2 },
            ],
            userRank: { rank_position: 0, score: 0 },
            userInList: null,
            total: 2,
          });
        }
      } catch (error) {
        console.log('⚠️ 排行榜查询出错，返回Mock数据', error);
        return ApiResponse.success({
          type: 'total',
          leaderboard: [],
          userRank: { rank_position: 0, score: 0 },
          userInList: null,
          total: 0,
        });
      }
    }

    // 获取查询参数
    const { searchParams } = new URL(request.url);
    const type = searchParams.get('type') || 'total'; // total, weekly, monthly
    const limit = parseInt(searchParams.get('limit') || '100');

    // 获取排行榜数据
    let leaderboard = [];
    if (type === 'weekly') {
      leaderboard = await LeaderboardDB.getWeeklyLeaderboard(limit);
    } else if (type === 'monthly') {
      leaderboard = await LeaderboardDB.getMonthlyLeaderboard(limit);
    } else {
      leaderboard = await LeaderboardDB.getTotalLeaderboard(limit);
    }

    // 获取当前用户排名
    const userRank = await LeaderboardDB.getUserRank(
      currentUser.userId, 
      type as 'total' | 'weekly' | 'monthly'
    );

    // 查找当前用户在榜单中的位置
    const userInList = leaderboard.find((u: any) => u.id === currentUser.userId);

    return ApiResponse.success({
      type,
      leaderboard,
      userRank: userRank || { rank_position: 0, score: 0 },
      userInList: userInList || null,
      total: leaderboard.length,
    });
  } catch (error) {
    console.error('获取排行榜错误:', error);
    return ApiResponse.serverError('获取排行榜失败');
  }
}

